package com.starsoft.frame.base.Interceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.starsoft.frame.base.bean.BaseAcount;
import com.starsoft.frame.base.bean.BaseUser;
import com.starsoft.frame.base.bean.UserContext;
import com.starsoft.frame.base.service.UserService;
import com.starsoft.frame.util.SpringContext;
import com.starsoft.frame.util.StringUtil;

public class LoginInterceptor implements HandlerInterceptor {

	private static Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
	
	@Autowired
	UserService us;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		HttpServletRequest hrequest=(HttpServletRequest) request;
		String path=hrequest.getServletPath();
		//排除登录页面
		if(path.contains("/base/login/")){
			return true;
		}
		//排除测试页面
		if(path.indexOf("/base/test/")>-1){
			return true;
		}
		//检验是否登录
		UserContext user=(UserContext)hrequest.getSession().getAttribute("user");
		if(user!=null && user instanceof UserContext){
			UserService.setUserContext(user);
		} else if(autoLogin(hrequest)){
		} else {
			HttpServletResponse hresponse=(HttpServletResponse) response;
			if(path.endsWith(".json")){
				hresponse.getWriter().append("{sucesse:'false',location:'"+hrequest.getContextPath()+"/base/login/login.jsp'}");	
			}else{
				hresponse.sendRedirect(hrequest.getContextPath()+"/base/login/login.jsp");
			}
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub

	}
	
	private boolean autoLogin(HttpServletRequest request){
		if(request==null || request.getCookies()==null){
			return false;
		}
		
		UserService us=SpringContext.getBean(UserService.class);
		String userName="";
		String userPwd="";
		String acountIdStr="";
		
		for (Cookie cookie : request.getCookies()) {
			if (cookie.getName().equals("userName")) {
				userName = cookie.getValue();
			}
			if (cookie.getName().equals("userPwd")) {
				userPwd = cookie.getValue();
			}
			if (cookie.getName().equals("acount")) {
				acountIdStr = cookie.getValue();
			}
		}
		BaseUser user = us.checkUser(userName, userPwd);
		if(user!=null){
			UserContext userContext = us.getUserContext(userName);
			request.getSession().setAttribute("user", userContext);
			try {
				if (!StringUtil.isEmpty(acountIdStr)) {
					Integer acountId = Integer.parseInt(acountIdStr);
					BaseAcount acount = us.getAcount(acountId);
					UserService.getUserContext().setAcount(acount);
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
			return true;
		}
		return false;
	}

}
